package org.smart4j.chapter1.plugin.security.aspect;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.smart4j.chapter1.annotation.Aspect;
import org.smart4j.chapter1.annotation.Controller;
import org.smart4j.chapter1.plugin.security.User;
import org.smart4j.chapter1.plugin.security.exception.AuthzException;
import org.smart4j.chapter1.proxy.AspectProxy;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @ClassName: 授权注解切面
 * @Description:
 * @Author: LynnZou
 * @Date: 2017/5/31
 */
@Aspect(Controller.class)
public class AuthzAnnotationAspect extends AspectProxy {

    /**
     * 定义一个基于授权功能的注解类数组
     */
    private static final Class[] ANNOTAION_CLASS_ARRAY = {User.class};

    @Override
    public void before(Class<?> cls, Method method, Object[] params) throws Throwable {
        //从目标类与目标方法中获取相应的注解
        Annotation annotation;
    }


    private Annotation getAnnotation(Class<?> cls,Method method){

        for (Class<? extends Annotation> annotaionClass:ANNOTAION_CLASS_ARRAY){
            //首先判断目标方法上是否带有授权注解
            if(method.isAnnotationPresent(annotaionClass)){
                return method.getAnnotation(annotaionClass);
            }

            //然后判断目标类上是否带有授权注解
            if(cls.isAnnotationPresent(annotaionClass)){
                return cls.getAnnotation(annotaionClass);
            }

        }

        //若目标方法与目标类上均为带有授权注解，则返回空对象
        return null;
    }

    private void handleUser(){
        Subject currentUser = SecurityUtils.getSubject();
        PrincipalCollection principals = currentUser.getPrincipals();
        if(principals == null || principals.isEmpty()){
            throw new AuthzException("当前用户尚未登陆");
        }
    }

}
